package com.bosssoft.hr.javase;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description: 按范围下载文件
 * @Author: wengyu
 * @CreateTime: 2022/05/13 15:42
 */
public class DownloadWithRange implements Runnable {

    private static final int TIME_OUT = 5000;
    // 请求地址
    private String urlLocation;
    // 保存地址
    private String filePath;
    // 开始位置
    private long start;
    // 结束位置
    private long end;

    public DownloadWithRange() {
    }

    DownloadWithRange(String urlLocation, String filePath, long start, long end) {
        this.urlLocation = urlLocation;
        this.filePath = filePath;
        this.start = start;
        this.end = end;
    }


    @Override
    public void run() {
        RandomAccessFile out = null;
        InputStream in = null;
        try {
            // 获取连接
            HttpURLConnection conn = getHttp();
            // 分段获取 状态返回 206
            conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
            File file = new File(filePath);
            out = new RandomAccessFile(file, "rw");
            out.seek(start);
            in = conn.getInputStream();


            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) >= 0) {
                out.write(b, 0, len);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (in != null){
                    in.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if (out != null){
                    out.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public HttpURLConnection getHttp() throws IOException {
        URL url = null;

        if (urlLocation != null && !"".equals(urlLocation)) {
            url = new URL(urlLocation);
        }

        assert url != null;
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIME_OUT);
        conn.setRequestMethod("GET");
        return conn;
    }
}
